package com.link.base.base.email.controller;

import com.link.base.base.email.model.EmailInfo;
import com.link.base.base.email.service.EmailService;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.service.BasicService;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/12 9:27
 */

@Controller
@RequestMapping("/link/email")
public class EmailController extends BasicController<EmailInfo> {

    @Resource
    private EmailService emailService;
    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Override
    public BasicService<EmailInfo> getBasicService() throws Exception {
        return emailService;
    }

    @RequestMapping("/myTest")
    @ResponseBody
    public Map<String, Object> myTest(@JsonParam EmailInfo enity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            map.put("success", true);
            map.put("message", "这是测试消息");
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @RequestMapping("/test")
    @ResponseBody
    public Map<String, Object> test(@JsonParam EmailInfo enity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            emailService.sendEmailByTemplate(enity);
            map.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }


    /**
     * 发送邮件
     * @author yipeng.zhu@hand-china.com
     * @param enity
     * @return
     * @throws
     * @date 2019/2/21 10:19
     * @version 1.0
     */
    @RequestMapping("/sendMail")
    @ResponseBody
    public Map<String, Object> sendMail(@JsonParam EmailInfo enity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> myfiles = multipartRequest.getFiles("uploadAttachment");
        List<File> fileList = new ArrayList<>(16);
        try {
            for (MultipartFile file : myfiles) {
                File f = multipartFileToFile(file);
                fileList.add(f);
            }
            enity.setFileList(fileList);
            emailService.sendMail(enity);
            map.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("msg", e.getMessage());
        } finally {
            try {
                deleteTemp(fileList);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
        return map;
    }

    /**
     * web接收的MultipartFile类型文件 转换成File的文件
     * @author yipeng.zhu@hand-china.com
     * @param file
     * @return
     * @throws
     * @date 2019/2/25 19:45
     * @version 1.0
     */
    public File multipartFileToFile(MultipartFile file) throws Exception {
        File f = null;
        if (file != null && file.getSize() > 0) {
            InputStream ins = file.getInputStream();
            f = new File(file.getOriginalFilename());
            inputStreamToFile(ins, f);
        }
        return f;
    }

    /**
     * 在项目根目录生成一个临时文件
     * @author yipeng.zhu@hand-china.com
     * @param ins
     * @param file
     * @return
     * @throws
     * @date 2019/2/25 19:46
     * @version 1.0
     */
    public void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            int len = 8192;
            while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 删除项目根目录下临时文件
     * @author yipeng.zhu@hand-china.com
     * @param fileList
     * @return
     * @throws
     * @date 2019/2/25 19:48
     * @version 1.0
     */
    public void deleteTemp(List<File> fileList) throws IOException {
        if (fileList != null && !fileList.isEmpty()) {
            for (File f : fileList) {
                Files.delete(f.toPath());
            }
        }
    }

    /**
     * 插入模板前 生成模板编码
     * @author yipeng.zhu@hand-china.com
     * @param entity
     * @return
     * @throws
     * @date 2019/2/21 10:19
     * @version 1.0
     */
    @Override
    public void beforInsert(EmailInfo entity, HttpServletRequest request) throws Exception {
        String code = "code";
        if (code.equals(entity.getAttr1())) {
            String emailCode = String.valueOf(keyGenerateDao.keyGenerate());
            entity.setEmailCode(emailCode);
        }

    }

}
